package jvm;

import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2021-02-20 17:14:00
 */
public class HClassLoader extends ClassLoader {

    private String classPath;

    public HClassLoader(String classPath) {
        this.classPath = classPath;
    }

    /**
     * 注意，只有类找不到才会用自定义加载器，能找到则由于双亲委派机制，从父类找了(此时的父类是应用类加载器)
     *  自定义加载器->应用类加载器->拓展类加载器->根加载器
     * @param name
     * @return
     * @throws ClassNotFoundException
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            byte[] data = loadByte(name);
            return defineClass(name, data, 0, data.length);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ClassNotFoundException();
        }
    }

    private byte[] loadByte(String name) throws Exception {
        name = name.replaceAll("\\.", "/");
        FileInputStream fis = new FileInputStream(classPath + "/" + name + ".class");
        int len = fis.available();
        byte[] data = new byte[len];
        fis.read(data);
        fis.close();
        //解密
//        data = TokenSignatureUtils.encryptByte(data);
        return data;
    }

}
